package com.zhouz.admin.app.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zhouz.admin.app.db.exception.TokenNoVildException;
import lombok.extern.log4j.Log4j2;

import java.util.*;

@Log4j2
public class JwtHelper {
	// 秘钥
	static final String SECRET = "X-APP-Token";
	// 签名是有谁生成
	static final String ISSUSER = "TTS";
	// 签名的主题
	static final String SUBJECT = "this is TTS token";
	// 签名的观众
	static final String AUDIENCE = "MINIAPP";
	// redis 存储jwt
	public static final String REDIST_JWT = "JWT-USER-";
	public static final String EXPIRE_TOKEN_PRE = "EXPIRE_TOKEN_PRE:";
	// TOKEN 过期时间
	public static final Integer expireHours = 8;
	// token 标识
	public static final String LOGIN_TOKEN_KEY = "TTS-APP-Token";

	public static final String LOGIN_TOKEN_KEY_CODE = "KJB-APP-Token-UserCode";

	public String createToken(String userId,String active){
		try {
		    Algorithm algorithm = Algorithm.HMAC256(SECRET);
		    Map<String, Object> map = new HashMap<String, Object>();
		    Date nowDate = new Date();
		    // 过期时间：2小时
		    Date expireDate = getAfterDate(nowDate,0,0,0,expireHours,0,0);
			//Date expireDate = getAfterDate(nowDate,0,0,0,0,0,5);
	        map.put("alg", "HS256");
	        map.put("typ", "JWT");
		    String token = JWT.create()
		    	// 设置头部信息 Header
		    	.withHeader(map)
		    	// 设置 载荷 Payload
		    	.withClaim("userId", userId)
		        .withIssuer(ISSUSER+active)
		        .withSubject(SUBJECT)
		        .withAudience(AUDIENCE)
		        // 生成签名的时间 
		        .withIssuedAt(nowDate)
		        // 签名过期的时间 
		        .withExpiresAt(expireDate)
		        // 签名 Signature
		        .sign(algorithm);
		    return token;
		} catch (JWTCreationException exception){
			exception.printStackTrace();
		}
		return null;
	}
	
	public String verifyTokenAndGetUserId(String token,String active) {
		try {
		    Algorithm algorithm = Algorithm.HMAC256(SECRET);
		    JWTVerifier verifier = JWT.require(algorithm)
		        .withIssuer(ISSUSER+active)
		        .build();
		    DecodedJWT jwt = verifier.verify(token);
		    Map<String, Claim> claims = jwt.getClaims();
		    Claim claim = claims.get("userId");
		    return claim.asString();
		} catch (TokenExpiredException exp){
			// token 过期
			//exp.printStackTrace();
			log.warn("token 过期,尝试刷新");
			throw exp;
		}catch (JWTVerificationException exception){
			//exception.printStackTrace();
			log.error("token验证失败");
			throw new TokenNoVildException(exception.getMessage());
		}
	}
	
	public  Date getAfterDate(Date date, int year, int month, int day, int hour, int minute, int second){
		if(date == null){
			date = new Date();
		}
		
		Calendar cal = new GregorianCalendar();
		
		cal.setTime(date);
		if(year != 0){
			cal.add(Calendar.YEAR, year);
		}
		if(month != 0){
			cal.add(Calendar.MONTH, month);
		}
		if(day != 0){
			cal.add(Calendar.DATE, day);
		}
		if(hour != 0){
			cal.add(Calendar.HOUR_OF_DAY, hour);
		}
		if(minute != 0){
			cal.add(Calendar.MINUTE, minute);
		}
		if(second != 0){
			cal.add(Calendar.SECOND, second);
		}
		return cal.getTime();
	}

	public static void main(String[] args) {
		JwtHelper helper = new JwtHelper();
		String token = helper.createToken("abcdabawerwer","sit");
		System.out.println(token);
		//String userId =helper.verifyTokenAndGetUserId(token);
		//System.out.println("通过token获取用户id"+userId);
		try {
			Thread.sleep(6000);
			//userId =helper.verifyTokenAndGetUserId(token);
			//System.out.println("6秒后 通过token获取用户id"+userId);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}
}
